package top.milkbox.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import top.milkbox.domain.PostLike;
import top.milkbox.domain.User;
import top.milkbox.service.PostLikeService;
import top.milkbox.mapper.PostLikeMapper;
import org.springframework.stereotype.Service;
import top.milkbox.service.UserService;
import top.milkbox.utils.GuoUtilsDate;

import java.util.function.Consumer;

/**
 * @author xiaoguo
 * @description 针对表【tb_post_like(帖子点赞表)】的数据库操作Service实现
 * @createDate 2022-11-21 17:31:09
 */
@Slf4j
@Service
public class PostLikeServiceImpl extends ServiceImpl<PostLikeMapper, PostLike>
        implements PostLikeService {

    @Autowired
    private PostLikeMapper postLikeMapper;

    @Autowired
    private UserService userService;

    @Override
    public int likeOrCancelLike(String token, int postId) {
        try {
            User user = userService.getUserFromRedis(token);
            // 查询点赞状态
            if (isLike(user.getUserId(), postId)) {
                log.debug("用户" + user.getUserId() + "已经点过赞了，准备取消点赞");
                // 删除操作，通过user_id和post_id删除数据
                QueryWrapper<PostLike> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_id", user.getUserId())
                        .eq("post_id", postId);
                return postLikeMapper.delete(queryWrapper) == 1 ? 2 : 0;
            } else {
                log.debug("用户" + user.getUserId() + "还没有点赞，准备点赞");
                // 插入操作
                PostLike postLike = new PostLike();
                postLike.setUserId(user.getUserId());
                postLike.setPostId(postId);
                postLike.setTime(GuoUtilsDate.getDateNow());
                return postLikeMapper.insert(postLike);
            }
        } catch (Exception e) {
            log.error("点赞取消点赞异常");
            return 0;
        }
    }

    @Override
    public boolean isLike(int userId, int postId) {
        QueryWrapper<PostLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("post_id", postId);
        return postLikeMapper.selectOne(queryWrapper) != null;
    }
}




